<template>
  <div id="wrapper"; style="background-color: #e0e3ff">

    <!-- 主体内容 -->
    <div style="position: relative;">

      <!-- 表格主体 -->
      <div class="main-content">
        <el-table :data="objs" stripe style="width: 100%">
          <!-- 表格列 -->
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="nickName" label="昵称"></el-table-column>
          <el-table-column prop="sex" label="性别"></el-table-column>
          <el-table-column prop="age" label="年龄"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button size="small" @click="init(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
            v-model:current-page="pageInfo.pageNum"
            :page-size="pageInfo.pageSize"
            :total="pageInfo.total"
            @current-change="loadTable"
            layout="prev, pager, next"
        />
      </div>

      <!-- 弹窗表单 -->
      <el-dialog v-model="showModal" :title="entity.id ? '编辑用户' : '新增用户'" @closed="resetForm">
        <el-form :model="entity" label-width="80px">
          <el-form-item label="姓名">
            <el-input v-model="entity.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="entity.nickName" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="entity.sex">
              <el-radio label="男" />
              <el-radio label="女" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model.number="entity.age" placeholder="请输入年龄" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="entity.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="entity.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="showModal = false">取消</el-button>
          <el-button type="primary" @click="update">确认</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 响应式数据
const authority = ref([])
const permission = ref([])
const name = ref('')
const user = ref(JSON.parse(localStorage.getItem('user')))
const objs = ref([])
const pageInfo = ref({})
const entity = reactive({ sex: '男' })
const showModal = ref(false)

// 计算属性
const preActive = computed(() => !pageInfo.value.hasPreviousPage)
const nextActive = computed(() => !pageInfo.value.hasNextPage)

// 导航菜单配置

// 方法
const loadTable = async (pageNum = 1) => {
  try {
    const res = await axios.get(`/userInfo/page/${name.value || 'all'}?pageNum=${pageNum}`)
    if (res.data.code === '0') {
      objs.value = res.data.data.list
      pageInfo.value = res.data.data
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

const init = (obj) => {
  if (!permission.value.includes(3)) {
    return ElMessage.warning('无操作权限')
  }
  Object.assign(entity, obj)
  showModal.value = true
}

const add = () => {
  if (!permission.value.includes(1)) {
    return ElMessage.warning('无添加权限')
  }
  resetForm()
  showModal.value = true
}

const update = async () => {
  try {
    const method = entity.id ? 'put' : 'post'
    const res = await axios[method]('/userInfo', entity)
    if (res.data.code === '0') {
      ElMessage.success(entity.id ? '更新成功' : '添加成功')
      showModal.value = false
      loadTable(pageInfo.value.pageNum)
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const del = (id) => {
  if (!permission.value.includes(2)) return ElMessage.warning('无删除权限')

  ElMessageBox.confirm('确认删除？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await axios.delete(`/userInfo/${id}`)
    if (res.data.code === '0') {
      ElMessage.success('删除成功')
      loadTable(pageInfo.value.pageNum)
    }
  }).catch(() => null)
}

const resetForm = () => {
  Object.assign(entity, { sex: '男' })
}

// 生命周期
onMounted(async () => {
  await loadTable(1)

  try {
    const [permRes, authRes] = await Promise.all([
      axios.get('/permission/2'),
      axios.get('/authority')
    ])
    permission.value = permRes.data.code === '0' ? permRes.data.data : []
    authority.value = authRes.data.code === '0' ? authRes.data.data : []
  } catch (error) {
    ElMessage.error('初始化失败')
  }
})
</script>

<style scoped>
@import '../css/common.css';
@import '../css/nav.css';

#wrapper {
  min-height: 100vh;
  background: #f0f2f5;
}

.sideMenu {
  height: 100vh;
  background: #fff;
  box-shadow: 2px 0 6px rgba(0,0,0,.1);
}

.header {
  background: linear-gradient(to bottom, #26a3de, #057db5);
  height: 60px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  color: white;
}

.main-content {
  padding: 20px;
  background: #fff;
  margin: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}
</style>